package com.shuozi.keyboardpopup;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static com.shuozi.keyboardpopup.KeyboardWithCommit.dpToPx;


public class KeyboardPopupWindow extends BaseKeyboardPopup {
    private static final String TAG = "KeyboardPopupWindow";
    private Context context;
    private View anchorView;
    private View parentView;
    private View faView;
    private EditText editText;
    private boolean isRandomSort = false;//数字是否随机排序

    private boolean ishasDot = true;//是否包含点
    private List<Integer> list = new ArrayList<>();
    private int[] commonButtonIds = new int[]{R.id.button00, R.id.button01, R.id.button02, R.id.button03,
            R.id.button04, R.id.button05, R.id.button06, R.id.button07, R.id.button08, R.id.button09};

    List editList;
    public interface ShowListener{

       void onShow(int height);
        void onDissmiss();
    }
    ShowListener showListener;

    public ShowListener getShowListener() {
        return showListener;
    }

    public void setShowListener(ShowListener showListener) {
        this.showListener = showListener;
    }

    /**
     * @param context
     * @param isRandomSort 数字是否随机排序
     *  @param ishasDot 是否包含点
     */
    public KeyboardPopupWindow(Context context,boolean isRandomSort,boolean ishasDot) {
        this.context = context;
        this.isRandomSort = isRandomSort;
        this.ishasDot = ishasDot;

        editList=new ArrayList();

    }

    public KeyboardPopupWindow(Context context, View anchorView, EditText editText, boolean isRandomSort,boolean ishasDot) {
        this.context = context;
        this.anchorView = anchorView;
        this.editText = editText;
        this.isRandomSort = isRandomSort;
        this.ishasDot = ishasDot;
        if (context == null || anchorView == null) {
            return;
        }
        editList=new ArrayList();
        initConfig();
        forbidDefaultSoftKeyboard();
        initView();

//                editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                Log.d(TAG, "数字输入框是否有焦点——>" + hasFocus);
//
//                refreshKeyboardOutSideTouchable(!hasFocus);// 需要等待页面创建完成后焦点变化才去显示自定义键盘
//
//                if (hasFocus) {//隐藏系统软键盘
//                    InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
//                    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
//                }
//
//            }
//        });
    }
    /**
     * @param context
     * @param anchorView
     * @param editText
     * @param isRandomSort 数字是否随机排序
     */
    public KeyboardPopupWindow(Context context, View anchorView, EditText editText, boolean isRandomSort) {
        this.context = context;
        this.anchorView = anchorView;
        this.editText = editText;
        this.isRandomSort = isRandomSort;
        if (context == null || anchorView == null) {
            return;
        }
        initConfig();
        forbidDefaultSoftKeyboard();
        initView();
    }

    private void initConfig() {
        setOutsideTouchable(false);
        setFocusable(false);
        setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    }

    /**
     * 禁止系统默认的软键盘弹出
     */
    private void forbidDefaultSoftKeyboard() {
        if (editText == null) {
            return;
        }
        if (android.os.Build.VERSION.SDK_INT > 10) {//4.0以上，使用反射的方式禁止系统自带的软键盘弹出
            try {
                Class<EditText> cls = EditText.class;
                Method setShowSoftInputOnFocus;
                setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(editText, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        editText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                if (this != null) {
                    setFocusable(true);//要先让popupwindow获得焦点，才能正确获取popupwindow的状态
                }


                if (!isShowing()) {

                    show();// 需要等待页面创建完成后焦点变化才去显示自定义键盘
                }else {

                }

            }
        });


    }

    @Override
    public void dismiss() {
        super.dismiss();


    }

    /**
     * 刷新自定义的popupwindow是否outside可触摸反应：如果是不可触摸的，则显示该软键盘view
     *
     * @param isTouchable
     */
    public void refreshKeyboardOutSideTouchable(boolean isTouchable) {
        setOutsideTouchable(isTouchable);

        if (!isTouchable) {
            Log.d(TAG, "执行show");
            show();
        } else {
            Log.d(TAG, "执行dismiss");
            dismiss();

        }
    }

    private void initView() {
        parentView = LayoutInflater.from(context).inflate(R.layout.keyboadview, null);
        faView= parentView.findViewById(R.id.faview);
        initKeyboardView(parentView);
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        setContentView(parentView);
    }

    private void initKeyboardView(View view) {
        ConstraintLayout dropdownLl = view.findViewById(R.id.dropdownLl);
        dropdownLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        //①给数字键设置点击监听
        for (int i = 0; i < commonButtonIds.length; i++) {
            final Button button = view.findViewById(commonButtonIds[i]);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int curSelection = editText.getSelectionStart();
                    int length = editText.getText().toString().length();
                    if (curSelection < length) {
                        String content = editText.getText().toString();
                        editText.setText(content.substring(0, curSelection) + button.getText() + content.subSequence(curSelection, length));
                        editText.setSelection(curSelection + 1);
                    } else {
                        editText.setText(editText.getText().toString() + button.getText());
                        editText.setSelection(editText.getText().toString().length());
                    }
                }
            });
        }

        //②给小数点按键设置点击监听
        Button buttonDot=  (Button)view.findViewById(R.id.buttonDot);
        if (ishasDot){
            buttonDot.setText(".");
            buttonDot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int curSelection = editText.getSelectionStart();
                    int length = editText.getText().toString().length();
                    if (curSelection < length) {
                        String content = editText.getText().toString();
                        editText.setText(content.substring(0, curSelection) + "." + content.subSequence(curSelection, length));
                        editText.setSelection(curSelection + 1);
                    } else {
                        editText.setText(editText.getText().toString() + ".");
                        editText.setSelection(editText.getText().toString().length());
                    }
                }
            });
        }else {

            buttonDot.setText("");
        }


        //③给叉按键设置点击监听
        view.findViewById(R.id.buttonCross).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int length = editText.getText().toString().length();
                int curSelection = editText.getSelectionStart();
                if (length > 0 && curSelection > 0 && curSelection <= length) {
                    String content = editText.getText().toString();
                    editText.setText(content.substring(0, curSelection - 1) + content.subSequence(curSelection, length));
                    editText.setSelection(curSelection - 1);
                }
            }

        });

//        Button buttonCross =  view.findViewById(R.id.buttonCross);
//        Drawable drawable = null;
//        drawable = ContextCompat.getDrawable(context,R.drawable.icondele);
//
//        drawable.setBounds(0, 0, dpToPx(25),
//                dpToPx(25));
//        buttonCross .setCompoundDrawables(null, drawable, null , null);

//        Html.ImageGetter imgGetterFromProject = new Html.ImageGetter() {
//            @Override
//            public Drawable getDrawable(String source) {
//                Drawable drawable = null;
//                int rId = Integer.parseInt(source);
//                drawable = ContextCompat.getDrawable(context,rId);
//
//                drawable.setBounds(0, 0, dpToPx(25),
//                        dpToPx(25));
//                return drawable;
//            }
//
//        };


//        SpannableString spanText = new SpannableString("1");
//        Drawable d = context.getResources().getDrawable(R.drawable.icondele);
//        int b = (int)buttonCross.getTextSize();
//        d.setBounds(0,0,b,b);
//        ImageSpan imageSpan = new ImageSpan(d,ImageSpan.ALIGN_BASELINE);
//        spanText.setSpan(imageSpan, 0,1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        buttonCross.setText(spanText);


        // 通过html获取项目资源图片
//
//        buttonCross.setText(Html.fromHtml("<img src=\""
//                + R.drawable.icondele + "\"/>", imgGetterFromProject, null));
    }


    public void show() {
        if (!isShowing() && anchorView != null) {
            setFocusable(false);
            setOutsideTouchable(false);
            doRandomSortOp();
            this.showAtLocation(anchorView, Gravity.BOTTOM, 0, 0);
        }
        if (showListener!=null){

            if (faView.getHeight()==0){
                faView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showListener.onShow(faView.getHeight());
                    }
                },300);
            }else {
                showListener.onShow(faView.getHeight());
            }


        }
        setFocusable(false);
    }

    /**
     * 随机分布数字
     */
    private void doRandomSortOp() {
        if (parentView == null) {
            return;
        }
        if (!isRandomSort) {
            for (int i = 0; i < commonButtonIds.length; i++) {
                final Button button = parentView.findViewById(commonButtonIds[i]);
                button.setText("" + i);
            }
        } else {
            list.clear();
            Random ran = new Random();
            while (list.size() < commonButtonIds.length) {
                int n = ran.nextInt(commonButtonIds.length);
                if (!list.contains(n)) {
                    list.add(n);//如果n不包涵在list中，才添加
                }
            }
            for (int i = 0; i < commonButtonIds.length; i++) {
                final Button button = parentView.findViewById(commonButtonIds[i]);
                button.setText("" + list.get(i));
            }
        }
    }


    public void refreshViewAndShow(Context context, View anchorView, EditText editText, boolean hasFocus) {
        this.context = context;
        this.anchorView = anchorView;
        this.editText = editText;
        if (context == null || anchorView == null) {
            return;
        }
        initConfig();
        forbidDefaultSoftKeyboard();
        initView();

        show();

//        refreshKeyboardOutSideTouchable(hasFocus);
    }

    public boolean isRandomSort() {
        return isRandomSort;
    }

    public void setRandomSort(boolean randomSort) {
        isRandomSort = randomSort;
    }

     @Override
    public void releaseResources() {
        this.dismiss();
        context = null;
        anchorView = null;
        if (list != null) {
            list.clear();
            list = null;
        }
         if (editList != null) {
             editList.clear();
             editList = null;
         }
    }
    public void configEditText(EditText editText){
        editList.add(editText);
    }


    public void onFocusChange(View view, boolean hasFocus,View faView) {


        if (KeyboardPopupHelper.getEditTextList().contains(view)){
            EditText editText1=(EditText)view;
            Log.e("aa","包含view");
            if (hasFocus) {//隐藏系统软键盘
                InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
            refreshViewAndShow(context,faView,editText1,hasFocus);
        }else {
            Log.e("aa","不包含view");
            dismiss();
        }
    }

}
